package cn.pku.edu.cs.ldn.util;

import java.io.File;

import android.os.Environment;
import android.util.Log;

public class FileUtil {
	private static final String TAG = "FileUtil";
	private static final boolean DEBUG = true;

	private static String localCacheDir = null;

	/**
	 * delete a local file, not a dir
	 * 
	 * @param path
	 * @return
	 */
	public static boolean deleteFile(String path) {
		boolean ret = false;
		if (path == null) {
			if (DEBUG)
				Log.e(TAG, "deleteFile: null path, r u serious?");
			return ret;
		}
		File file = new File(path);
		if (file.isFile()) {
			ret = file.delete();
			if (DEBUG)
				Log.v(TAG, "deleteFile: file.delete() returns " + ret);
		} else {
			if (DEBUG)
				Log.v(TAG, "deleteFile: not a file " + path);
			ret = false;
		}
		if (DEBUG)
			Log.v(TAG, "deleteFile: result " + ret);
		return ret;
	}

	public static boolean isRemoteFileCached(String remotePath) {
		if (remotePath == null) {
			return false;
		}
		String localPath = getLocalCachePath(remotePath);

		boolean ret = isLocalFileExist(localPath);
		return ret;
	}

	public static boolean isLocalFileExist(String localPath) {
		File file = new File(localPath);
		return file.exists();
	}

	/**
	 * with NO "/" at the end
	 * 
	 * @return
	 */
	public static String getLocalCacheDir() {
		if (localCacheDir == null) {
			localCacheDir = Environment.getExternalStorageDirectory()
					.getAbsolutePath() + "/LDNAndroid";
		}
		File file = new File(localCacheDir);
		if (file.exists() == false) {
			file.mkdir();
		}
		return localCacheDir;
	}

	public static String getLocalCachePath(String remotePath) {
		if (remotePath == null) {
			return null;
		}

		// is already a local path
		if (remotePath.startsWith("/")) {
			return remotePath;
		}
		String md5 = MD5Util.getMD5String(remotePath);
		String localPath = getLocalCacheDir() + "/" + md5;
		return localPath;
	}

}
